package org.jash.shop2112.cart

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.jash.shop2112.entity.CartItem
import org.jash.shop2112.entity.Category
import org.jash.shop2112.entity.Goods
import org.jash.shop2112.mvvm.BaseViewModel

class CartViewModel:BaseViewModel() {
    val cartsLiveData by lazy { MutableLiveData<List<CartItem>>() }
    val deleteLiveData by lazy { MutableLiveData<Int>() }
    fun loadCarts() {
        viewModelScope.launch {
            try {
                val res = service.getCarts()
                if (res.code == 200) {
                    cartsLiveData.postValue(res.data)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
    fun deleteCart(id:Int) {
        viewModelScope.launch {
            try {
                val res = service.deleteCart(mapOf("ids" to id.toString()))
                if (res.code == 200) {
                    deleteLiveData.postValue(id)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
}